
const query = require('../config/connection');
const koa2Req = require('koa2-request');
//新增会员信息
async function addMemberService (ctx, params) {
  let param = [];
  let key = [];
  for (let item in params) {
    let value = "'" + params[item] + "'"
    param.push(value)
    key.push(item)
  }
  let sql = `insert into member (${key.join(",")}) values(${param.join(",")})`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    };
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    };
  }
}
//获取会员信息
async function getMemberListService (ctx) {
  let sql = `select * from member`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    };
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    };
  }
}
//获取用户openId   todo这里换成你们自己的appId和appsecret  
async function getUserOpenIdService (ctx, params) {
  const appId = 'wxbe873efd6206a0cd'; // AppID(小程序ID)wx255ec178c1a6de9d
  const appSecret = '32d9dfa4e9d77cf6c1ce5adaea9af314';// AppSecret(小程序密钥)

  try {
    const res = await koa2Req({
      url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${params.code}&grant_type=authorization_code`
    }) // 如满足条件，这一步就可以获取uid
    let data = JSON.parse(res.body);
    ctx.body = {
      "success": true,
      "data": data
    };
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    };
  }
}
module.exports = {
  addMemberService,
  getMemberListService,
  getUserOpenIdService
};





